package com.mashibing.juc.c_011;

import java.util.concurrent.TimeUnit;

/**
 * synchronized程序出现异常默认情况下锁会被自动释放
 * lock需要手动释放锁
 * Atomic、lock使用的都是自旋锁
 * @author: Yuanzt
 * @Date: 2021/3/24
 */
public class T {

    int count = 0;
    synchronized void m(){
        System.out.println(Thread.currentThread().getName() + " start");
        while (true){
            count++;
            System.out.println(Thread.currentThread().getName() + " count " + count);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

//            try {
                if (count == 5){
                    int i = 1/0;//此处程序出现异常，锁将会被释放，想要不被释放，可以在这里catch，然后循环继续
                    System.out.println(i);
                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }
    }

    public static void main(String[] args) {
        T t = new T();

        new Thread(()->{t.m();},"t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{t.m();},"T2").start();
    }
}
